//
//  AllJobInfoViewController.m
//  allJodInfo
//
//  Created by 徐宏飞 on 16/5/19.
//  Copyright © 2016年 徐宏飞. All rights reserved.
//

#import "AllProjectController.h"

#import "ProjectWaitingTableViewCell.h"          //等待接单
#import "PorjectNegotiationTableViewCell.h"      //平台协商中
#import "ProjectGoingTableViewCell.h"            //正在进行的项目
#import "ProjectCompleteTableViewCell.h"         //已完成的订单&成功
#import "ProjectFailureTableViewCell.h"          //已完成的订单&失败

#import "RefuseViewController.h"                 //拒单
#import "AllProjectInfoModel.h"






static NSString *projectWaitingTableViewCell_ID     = @"ProjectWaitingTableViewCell";
static NSString *porjectNegotiationTableViewCell_ID = @"PorjectNegotiationTableViewCell";
static NSString *projectGoingTableViewCell_ID       = @"ProjectGoingTableViewCell";
static NSString *projectCompleteTableViewCell_ID    = @"ProjectCompleteTableViewCell";
static NSString *projectFailureTableViewCell_ID     = @"ProjectFailureTableViewCell";



@interface AllProjectController ()<UITableViewDelegate,
                                    UITableViewDataSource,
                                    ProjectWaitingTableViewCellDelegate,
                                    NetworkToolerDelegate,
                                    RefuseViewControllerDelegate
                                    >

@property (weak, nonatomic) IBOutlet UITableView *allJobInfoTableView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segment;



@property (nonatomic, strong) NSMutableArray *waitingArray;     //等待接单
@property (nonatomic, strong) NSMutableArray *negotiationArray; //平台协商
@property (nonatomic, strong) NSMutableArray *goingArray;       //正在进行的
@property (nonatomic, strong) NSMutableArray *completedArray;   //已完成
@property (nonatomic, strong) NetworkTooler *network;
@property (nonatomic, strong) ZhuangxiuManager *manager;
@property (nonatomic, assign) NSInteger loadpage;               //页码
@property (nonatomic, assign) NSInteger total;                  //列表总个数

@property (nonatomic, assign) ProjectStateType projectState;    //四种请求类型
@property (nonatomic, assign) ALLPROJECTREQUSTTYPE RequstType;  //具体请求类型





@end





@implementation AllProjectController



#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"我的所有工程";
    _network  = [NetworkTooler new];
    _waitingArray = [NSMutableArray array];
    _negotiationArray = [NSMutableArray array];
    _goingArray = [NSMutableArray array];
    _completedArray = [NSMutableArray array];

    
    
    //等待接单
    [self.allJobInfoTableView registerNib:[UINib nibWithNibName:@"ProjectWaitingTableViewCell" bundle:nil] forCellReuseIdentifier:projectWaitingTableViewCell_ID];

    //平台协商中
    [self.allJobInfoTableView registerNib:[UINib nibWithNibName:@"PorjectNegotiationTableViewCell" bundle:nil] forCellReuseIdentifier:porjectNegotiationTableViewCell_ID];
    
    //正在进行的项目
    [self.allJobInfoTableView registerNib:[UINib nibWithNibName:@"ProjectGoingTableViewCell" bundle:nil] forCellReuseIdentifier:projectGoingTableViewCell_ID];
    
    //已完成的订单&成功
    [self.allJobInfoTableView registerNib:[UINib nibWithNibName:@"ProjectCompleteTableViewCell" bundle:nil] forCellReuseIdentifier:projectCompleteTableViewCell_ID];
    
    //已完成的订单&失败
    [self.allJobInfoTableView registerNib:[UINib nibWithNibName:@"ProjectFailureTableViewCell" bundle:nil] forCellReuseIdentifier:projectFailureTableViewCell_ID];
    
    
    self.allJobInfoTableView.allowsSelection = NO;
    //默认是等待接单
    self.projectState = projectStateTypeWaiting;
    self.allJobInfoTableView.tableFooterView = [UIView new];

    
    self.manager = [ZhuangxiuManager shareManager];
//    self.loadpage = 1;
//    self.projectState = projectStateTypeWaiting;
//    [self getWorkerOrderList];
//    
    
    __weak AllProjectController *weakself = self;
    
    _allJobInfoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //        self.page = 0;
        
        [weakself updateNewData];
    }];
    
    _allJobInfoTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakself updateMoreData];
    }];
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    
    
    
    self.segment.tintColor = [UIColor clearColor];
    
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:12*WID],
                                             NSForegroundColorAttributeName: COLOR_THEHE};
    [self.segment setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];
    
    //设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:12*WID],
                                               NSForegroundColorAttributeName: [UIColor darkGrayColor]};
    [self.segment setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    
    self.segment.layer.cornerRadius = 10;
    self.segment.layer.masksToBounds = YES;
    
    [MobClick beginLogPageView:@"AllWork"];//("PageOne"为页面名称，可自定义)
    
    self.loadpage = 1;
//    self.projectState = projectStateTypeWaiting;
    [self getWorkerOrderList];

}



- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"AllWork"];
}

#pragma mark - Data
- (void)getWorkerOrderList{
    
    NSString *status = [NSStringchange projectTypeWith:self.projectState];
    
    
    NSDictionary *parameters = @{
                                 
                                 @"status":status,
                                 @"session_id":self.manager.sessionid,
//                                   @"session_id": @"1018c064e6df6cdcb3a5c1fb58566a49",
                                 @"rows":[NSString stringWithFormat:@"%d",listConut],
                                 @"page": [NSString stringWithFormat:@"%ld",self.loadpage]

                                 };
    
    NSLog(@"请求参数:%@", parameters);
    _network.delegate = self;
    
    [_network parameters:parameters withURL:getWorkerOrderList_show  withIsPaparameters:YES];
    
    
}

//接单请求
- (void)respondRqust:(NSString *)order_id{
    
    
    self.RequstType = ALLPROJECTREQUSTTYPERESPOND;
    
    NSDictionary *parameters = @{
                                 @"session_id":self.manager.sessionid,
                                 @"order_id":order_id
                                 };
    
    
    _network.delegate = self;
    
    [_network parameters:parameters withURL:orderAcceptOrder_show  withIsPaparameters:YES];
    
    
}
//拒单请求
- (void)RefuseRqustOrdid:(NSString *)order_id withReason:(NSString *)reason{
    
    
    self.RequstType = ALLPROJECTREQUSTTYPEREFUSE;
    
    NSDictionary *parameters = @{
                                 @"session_id":self.manager.sessionid,
                                 @"order_id":order_id,
                                 @"reason":reason
                                 };
    
    
    _network.delegate = self;
    
    [_network parameters:parameters withURL:orderDenyOrder_show  withIsPaparameters:YES];
    
    
}


#pragma mark - NetworkToolerDelegate
- (void)returnData:(id)data{
    
    

    [self endRefresh];
    self.bgView.hidden = YES;
    if (isNSDictionary) {

       
        if (_loadpage == 1) {
            [self.waitingArray removeAllObjects];
            [self.negotiationArray removeAllObjects];
            [self.goingArray removeAllObjects];
            [self.completedArray removeAllObjects];
        }
       
        NSArray *array = [data objectForKey:@"data"];
        if (array.count==0) {
            [self.waitingArray removeAllObjects];
            [self.negotiationArray removeAllObjects];
            [self.goingArray removeAllObjects];
            [self.completedArray removeAllObjects];
            [self.allJobInfoTableView reloadData];
            _total = 0;
            self.bgView.hidden = NO;

            return;

        }
        _total =[[data objectForKey:@"total"] integerValue];
        
        for (NSMutableDictionary *dic in array) {
            AllProjectInfoModel *model = [AllProjectInfoModel modelWithDictionary:dic];
            
            switch (self.projectState) {
                    
                case projectStateTypeWaiting:
                    
                    [self.waitingArray addObject:model];
                    break;
                    
                    
                case projectStateTypeNegotiation:
                    [self.negotiationArray addObject:model];
                    break;
                    
                case projectStateTypeGoing:
                    
                    [self.goingArray addObject:model];
                    
                    break;
                    
                case projectStateTypeCompleted:
                    [self.completedArray addObject:model];
                    break;
                    
                default:
                    
                    break;
                    
            }
            
            
        }
            [self.allJobInfoTableView reloadData];
        if (self.loadpage == 1) {
            
            NSIndexPath *index = [NSIndexPath indexPathForItem:0 inSection:0];
            [self.allJobInfoTableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
     


//返回不是字典
    }else{
    
        switch (self.RequstType) {
                
            case ALLPROJECTREQUSTTYPERESPOND:
                
                [GiabHUD showTimedAlertWithTitle:nil text:@"接单成功" withTimeout:1.5];
                _loadpage = 1;
                [self getWorkerOrderList];
                break;
                
            case ALLPROJECTREQUSTTYPEREFUSE:
                [GiabHUD showTimedAlertWithTitle:nil text:@"拒单成功" withTimeout:1.5];

                _loadpage = 1;

                [self getWorkerOrderList];

                break;
                
            default:
                
                break;
        
            
        }
    }
    
}

- (void)returnRequestError:(NSError *)error{
    
    
    self.bgView.hidden = NO;

    [self endRefresh];
    
}

- (void)returnMsg:(NSString *)Msg{
    
    [self endRefresh];

    if ([Msg isEqualToString:@"你的网络有问题哦!"]) {
        self.bgView.hidden = NO;
        [self.waitingArray removeAllObjects];
        [self.negotiationArray removeAllObjects];
        [self.goingArray removeAllObjects];
        [self.completedArray removeAllObjects];

//        [self.imgCaroselArrays removeAllObjects];
        [_allJobInfoTableView reloadData];
        return;
    }
   
    
    [self showAlertWithTitle:@"温馨提示" message:Msg cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
    
    
}









#pragma mark - UItableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
//    if (self.enableReturnButton) {

    switch (self.projectState) {
            
        case projectStateTypeWaiting:
            
            return self.waitingArray.count;
            break;
            
            
        case projectStateTypeNegotiation:
            
            return self.negotiationArray.count;
            break;
            
        case projectStateTypeGoing:
            
            return self.goingArray.count;
            break;
        
        case projectStateTypeCompleted:
            
            return self.completedArray.count;
            break;
            
        default:
            return 0;
            break;
    
    }
    
//    }
    
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    switch (_projectState) {
        case projectStateTypeWaiting:
            return 120;
            break;
        case projectStateTypeNegotiation:
            return 120;
            break;
        case projectStateTypeGoing:
            return 130;
            break;
        case projectStateTypeCompleted:
            //判断项目状态
            
            if (self.completedArray.count>0) {

            AllProjectInfoModel *model = [self.completedArray objectAtIndex:indexPath.row];
                
            if ([model.status isEqualToString:@"ending"]) {
                
                
                    return 170;
            
                } else {
                
                    return 90;
           
                }
           
            }else{
        
            
                return 0;

            }
            
            break;
        default:
            return 0;
            break;
    }
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    switch (_projectState) {
        case projectStateTypeWaiting:
        {
            if (self.waitingArray.count>0) {

        AllProjectInfoModel *model = [self.waitingArray objectAtIndex:indexPath.row];

            ProjectWaitingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:projectWaitingTableViewCell_ID];
            cell.model = model;
            cell.delegate = self;
                
            return cell;
        
            }
        }
            break;
            
        case projectStateTypeNegotiation:
        {
            if (self.negotiationArray.count>0) {
                
            
            AllProjectInfoModel *model = [self.negotiationArray objectAtIndex:indexPath.row];

            PorjectNegotiationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:porjectNegotiationTableViewCell_ID];
            cell.model = model;

                return cell;
            }
        }
            break;
            
        case projectStateTypeGoing:
        {
            if (self.goingArray.count>0) {

            AllProjectInfoModel *model = [self.goingArray objectAtIndex:indexPath.row];

            ProjectGoingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:projectGoingTableViewCell_ID];
            cell.model = model;

            return cell;
            
            }
        }
            break;
        case projectStateTypeCompleted:


        {
            if (self.completedArray.count>0) {
                
                AllProjectInfoModel *model = [self.completedArray objectAtIndex:indexPath.row];

                if ([model.status isEqualToString:@"ending"]) {
                    
                    ProjectCompleteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:projectCompleteTableViewCell_ID];
                    cell.model = model;

                    return cell;
                
                    }else {
                   //失败
                    ProjectFailureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:projectFailureTableViewCell_ID];
                    cell.model = model;
                    return cell;
                    }
            
            }else{
            
                return nil;
            }

    
            break;
        }
    
       default:
            return nil;
            break;
    }
    
    return nil;
    
    
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}



#pragma mark - CustomDelegate
- (void) _waitingTableViewCellClick:(NSInteger)type order_id:(NSString *)order_id{
    switch (type) {
        case 0:
        {
            
            [self respondRqust:order_id];
            
        }
            break;
            
        case 1:
        {
            //拒单
            
            RefuseViewController *refuse = [RefuseViewController new];
            refuse.orderID = order_id;
            refuse.delegate = self;
            refuse.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:refuse animated:YES];
        }
            break;
            
        case 2:
        {
            //协商
            [self actionAlertWithMessage:@"tel://8008808888"];
        }
            break;
            
            
        default:
            break;
    }
    
    
    
}

#pragma mark - RefuseViewControllerDelegate

-(void)returnReson:(NSString *)reson withOrdID:(NSString *)ordid{


    if (reson.length>0 && ordid.length>0) {
        [self RefuseRqustOrdid:ordid withReason:reson];
    }
    

}







#pragma mark - event response
- (IBAction)segmentedAction:(id)sender {
    
    if ([sender isKindOfClass:[UISegmentedControl class]]) {
        UISegmentedControl * segment = sender;
        
            
        switch (segment.selectedSegmentIndex) {
            case 0:
                self.projectState = projectStateTypeWaiting;
                
                break;
                
            case 1:
                self.projectState = projectStateTypeNegotiation;
                
                break;
                
            case 2:
                self.projectState = projectStateTypeGoing;
                
                break;
                
            case 3:
                self.projectState = projectStateTypeCompleted;
                
                break;
                
                
                
            default:
                break;
        }
        
        
//        NSIndexPath *index = [NSIndexPath indexPathForItem:0 inSection:0];
//        [self.allJobInfoTableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
//        [self.allJobInfoTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        self.loadpage = 1;
        [self getWorkerOrderList];
    }
}



#pragma mark - private methods
- (void)actionAlertWithMessage:(NSString *)msg{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"拨打客服电话协商!" message:@"10086" preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alertC animated:YES completion:^{
        NSLog(@"页面跳转完成");
    }];
    
    //添加一个确定按钮
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"执行打电话");
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:msg]];
        
        
    }];
    //添加提示按钮
    [alertC addAction:alertA];
}


-(void)updateNewData{
    
    _loadpage = 1;
    [self getWorkerOrderList];
    
    
}

-(void)updateMoreData{
    
    _loadpage++;
    
    if (_loadpage <= (int)((_total/listConut)+1)) {
        
        [self getWorkerOrderList];
    }else{
        [_allJobInfoTableView.mj_footer endRefreshingWithNoMoreData];
    }
}



-(void)endRefresh{
    [_allJobInfoTableView.mj_header endRefreshing];
    [_allJobInfoTableView.mj_footer endRefreshing];
}









#pragma mark - gettsers and setters








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
